#!/bin/bash
#
#  openmediavault-virtualbox: auto start sessions when booting and save 
#                sessions when host is stopped
#
#

### BEGIN INIT INFO
# Provides:          openmediavault-virtualbox
# Required-Start:    vboxdrv $local_fs
# Required-Stop:     vboxdrv $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       Controls VirtualBox sessions
### END INIT INFO


. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions


OMV_VBOX_CONFIG=${OMV_VBOX_CONFIG:-"/etc/default/virtualbox"}
OMV_VBOX_USER=${OMV_VBOX_USER:-"vbox"}

# Enable/disable service
if [ "$(omv_config_get "//services/virtualbox/enable")" != "1" ]; then
	exit 0
fi

start()
{
   # Get all autostart machines
   MACHINES=$($su_command "VBoxManage list vms | awk '{ print \$NF }' | sed -e 's/[{}]//g'")
   for UUID in $MACHINES; do
      STARTUP=$($su_command "VBoxManage getextradata $UUID 'pvbx/startupMode'" | awk '{ print $NF }')
      if [ "${STARTUP}" == "auto" ]; then
         $su_command "VBoxManage startvm $UUID --type headless" >>/var/log/vb.log
      fi
   done
}

stop()
{
   # vms are saved, instead of stopped.
   MACHINES=$($su_command "VBoxManage list runningvms | awk '{ print \$NF }' | sed -e 's/[{}]//g'")
   for UUID in $MACHINES; do
      echo "openmediavault-virtualbox: saving machine ${UUID} state"
      $su_command "VBoxManage controlvm $UUID savestate" >>/var/log/vb.log
   done

}

status()
{
   $su_command "VBoxManage list runningvms"
}
restart()
{
  stop
  start
}


# Implementation of user control, execute several commands as another (predefined) user,
su_command="su - ${OMV_VBOX_USER} -c"

#
# Check for a commandline option
#
case "$1" in
start)
  start
  ;;
stop)
  stop
  ;;
status)
  status
  ;;
restart)
  restart
  ;;  
*)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
  ;;  
esac

exit 0

